package com.probiz.estore.content.service.impl;

import java.util.List;

import com.probiz.estore.common.model.content.Subscriber;
import com.probiz.estore.content.dao.SubscriberDao;
import com.probiz.estore.content.service.SubscriberManager;
import com.probiz.estore.core.service.impl.GenericManagerImpl;


/**
 * Manager implementation for Subscriber, responsible for business processing, and communicate between web and persistence layer.
 */
public class SubscriberManagerImpl extends GenericManagerImpl<Subscriber> implements SubscriberManager {

	private SubscriberDao subscriberDao = null;

	/**
	 * @param subscriberDao
	 *            the subscriberDao to set
	 */
	public void setSubscriberDao(SubscriberDao subscriberDao) {
		this.subscriberDao = subscriberDao;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.service.impl.GenericManagerImpl#init()
	 */
	@Override
	protected void initManager() {
		dao = subscriberDao;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.service.impl.GenericManagerImpl#preDelete(java.lang.Object)
	 */
	@Override
	protected void preDelete(Subscriber entity) {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.service.impl.GenericManagerImpl#preSave(java.lang.Object)
	 */
	@Override
	protected void preSave(Subscriber entity) {

	}
	
	public List<Integer> getSubscribedNewsletterGroupIdsByEmail(String email){
		if(email==null)
			return null;
		return subscriberDao.getSubscribedNewsletterGroupIdsByEmail(email);
	}
	
	/**
	 * 订阅者是否存在
	 * @param email
	 * @return 存在返回true, 否则返回false
	 */
	public boolean isSubscriberExist(String email){
		long subscriptions = this.dao.countByPropertyCaseSensitive("email", email);
		return subscriptions>0;
	}
	
	/**
	 * 删除指定email订阅者的所有订阅
	 * @param email
	 */
	public void removeAllSubscriptions(String email){
		List<Subscriber> subs = this.dao.listByPropertyCaseSensitive("email", email);
		for(Subscriber sub:subs){
			this.delete(sub);
		}
	}
	
	/**
	 * 获取分页email列表
	 * @param pageNo
	 * @param pageSize
	 * @param newsletterGroupIds 所在消息组id列表
	 * @return
	 */
	public List<String> searchEmails(int pageNo, int pageSize, List<String> newsletterGroupIds){
		return this.subscriberDao.searchEmails(pageNo, pageSize, newsletterGroupIds);
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.content.service.SubscriberManager#addSubscriber(java.lang.String, java.lang.Integer)
	 */
	public void addSubscriber(String email, Integer groupId){
		Subscriber subscriber = (Subscriber)this.subscriberDao.findUnique("from Subscriber where email = binary('"+email+"') and newsletterGroupId = "+groupId);
		if(null == subscriber){
			subscriber = new Subscriber();
			subscriber.setEmail(email);
			subscriber.setNewsletterGroupId(groupId);
			this.save(subscriber);
		}
		
	}
}
